﻿using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Kaleida.ServiceMonitor.Model;
using Kaleida.ServiceMonitor.Model.Runtime;

namespace Kaleida.ServiceMonitor.UI.NotificationPanels
{
    [PanelName("Debug")]
    public partial class DiagnosticsPanel : UserControl//, IApplicationNotificationPanel
    {
        private ServiceMonApplication instance;

        public DiagnosticsPanel()
        {
            InitializeComponent();
        }

        public void Initialise(ServiceMonApplication applicationInstance)
        {
            instance = applicationInstance;
        }

        public Control GetPanelControl()
        {
            return this;
        }

        public void RefreshContent()
        {
            var debugInfo = new StringBuilder();
            debugInfo.AppendLine("Monitors");
            debugInfo.Append(string.Join("\r\n", instance.Monitors.Select(BuildMonitorDebugInfo)));

            if (instance.CurrentCompilation != null && instance.CurrentCompilation.Succeeded)
            {
                debugInfo.AppendLine("Modules");
                debugInfo.Append(string.Join("\r\n", instance.CurrentCompilation.CompiledScript.AllScriptModules.Select(BuildMonitorDebugInfo)));
            }

            textBox.Text = debugInfo.ToString();
        }

        public string PanelName
        {
            get { return "Debug - all"; }
        }

        private static string BuildMonitorDebugInfo(Monitor monitor)
        {
            var summary = new StringBuilder();
            summary.AppendFormat("Module Name='{0}', ", monitor.CompiledModule.Name);
            summary.AppendFormat("Operations Count='{0}', ", monitor.CompiledModule.Operations.Count());
            summary.AppendFormat("PollInterval='{0}', ", monitor.CompiledModule.PollInterval);
            summary.AppendFormat("IsMonitoring='{0}', ", monitor.State.IsMonitoring);
            summary.AppendLine();
            return summary.ToString();
        }

        private static string BuildMonitorDebugInfo(CompiledScriptModule module)
        {
            var summary = new StringBuilder();
            summary.AppendFormat("Module Name='{0}', ", module.Name);
            summary.AppendFormat("PollInterval='{0}', ", module.PollInterval);
            summary.AppendFormat("Operations Count='{0}', ", module.Operations.Count());
            
            summary.AppendLine();
            return summary.ToString();

        }

    }
}
